package com.xiaoyu.base.app;

import android.os.Build;
import android.text.TextUtils;
import android.widget.Toast;

import com.xiaoyu.base.view.ToastCompat;

import in.srain.cube.app.lifecycle.AppActivityLifecycleCallbacks;
import in.srain.cube.concurrent.SimpleTask;

public class GlobalUI {

    private static GlobalUI sInstance;

    public static synchronized GlobalUI getInstance() {
        if (sInstance == null) {
            sInstance = new GlobalUI();
        }
        return sInstance;
    }

    public void showToast(int stringResId) {
        showToast(AppContext.getString(stringResId));
    }

    public void showToast(CharSequence message) {
        showToast(message, true);
    }

    public void showToastForLong(CharSequence message) {
        showToast(message, false);
    }

    public void showToast(CharSequence message, boolean isShort) {
        if (!AppActivityLifecycleCallbacks.getInstance().isAppInForeground()) {
            return;
        }
        if (TextUtils.isEmpty(message)) {
            return;
        }
        try {
            SimpleTask.post(() -> {
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) {
                    ToastCompat.makeText(AppContext.getContext(), message, isShort ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(AppContext.getContext(), message, isShort ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG).show();
                }
            });
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}
